import React from 'react';
import {Modal , Select,Upload ,message, Button, InputNumber,Input, Form, Icon,Popover } from 'antd';
import _ from 'lodash';
const Option = Select.Option;
const createForm = Form.create;
const FormItem = Form.Item;
import {
  fetchPatients,
  createImage,
  API_URL,
  DICOMS,
  _validate,
  formItemLayout,
  uploadChangeHandle,
  deleteDicom
} from '../store/actions'
import PatientAdd from './formEditPatient'
let dicomUpload = {
    all:0,
    once:0
}
class NewPatient extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            visible: false
        };
        this.handleSubmit = this.handleSubmit.bind(this);
        this.showModal = this.showModal.bind(this);
        this.hideModal = this.hideModal.bind(this)
    }
    handleSubmit(v) {
        this.props.addNewPatient(v);
        this.hideModal();
    }

    showModal() {
        this.setState({ visible: true });
    }

    hideModal() {
        this.setState({ visible: false });
    }
    render(){
        return (
            <div>
                <Button type="primary" onClick={this.showModal}>新增亲友信息</Button>
                <Modal title="新增亲友信息"
                   visible={this.state.visible}
                   onCancel={this.hideModal}
                   footer=""
                >
                    <PatientAdd
                        user={this.props.user}
                        dispatch={this.props.dispatch}
                        _r = {this.context.router}
                        onSub={this.handleSubmit}
                        onCancel={this.hideModal}
                        isModal={true}
                    />
                </Modal>
            </div>
        )
    }
}
NewPatient = createForm()(NewPatient);
function randomCode(addtion){
    return (+new Date() + Math.floor(Math.random() * 999999)).toString(36)+((addtion && addtion)|| '');
}
class FormAddImage extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            choosePatient: true,
            readyForUpload: false,
            user:this.props.user,
            patients:this.props.patients.items || [],
            patientsOPT:[],
            defValue:false,
            pid:'',
            uuid:randomCode(this.props.user.user.account_id),
            submitDisabled: false,
            fileList:{}
        };
        this.handleSubmit = this.handleSubmit.bind(this);
        this.resetFields = this.resetFields.bind(this);
        this.createPatientsSelect = this.createPatientsSelect.bind(this);
        this.normFile = this.normFile.bind(this);
        this.uploadChange = this.uploadChange.bind(this);
        this.addNewPatient = this.addNewPatient.bind(this)
    }
    componentWillMount(){
        const _this=this,
            _user = _this.props.user,
            uid = _user.user.user_id,
            status = 1,
            opts = {
                userid: uid,
                status: status
            };
        if(this.props.patients.items.length < 1){
            this.props.dispatch(fetchPatients(opts,function(res){
                _this.setState({
                    patients:res.content.list
                })
            }));
        }else{
            _this.setState({
                patients:this.props.patients.items
            })
        }
    }
    componentWillReceiveProps(nextProp){
        this.setState({
            patients: nextProp.patients.items,
            user:nextProp.user
        })
    }
    createPatientsSelect(props){
        const _p = this.state.patients,
          _op = _.map(_p,__p=>{
            if(__p.status == 1){
               return <Option key={__p.id} value={__p.id}>{__p.name || '--'}</Option>
            }
        });
        if(_op.length < 1){
            return (<div>您还没有添加亲友，点击下方按钮可以添加亲友信息</div>)
        }else{
            if(!this.state.defValue){
                return (
                  <Select
                    {...props}
                    placeholder = "请选择亲友"
                    style={{ width: '60%' }}
                  >
                      {_op}
                  </Select>
                )
            }else{
                return (
                  <Select
                    {...props}
                    defaultValue = {this.state.defValue}
                    placeholder = "请选择亲友"
                    style={{ width: '60%' }}
                  >
                      {_op}
                  </Select>
                )

            }
        }
    }
    resetFields(){
        this.props.form.resetFields()
    }
    handleSubmit(e) {
        const _this = this;
        _validate(e,_this,function(v){
            delete v.upload;
            delete v.files_report;
            let _sendDate = {
                batchId:_this.state.uuid
            };
            /*const report = _.isArray(_this.state.attachment)?_this.state.report:false;
            if(report && report.length > 0){
                _sendDate.report_attachments = report
            }*/
            if(_this.state.attachment && _.isArray(_this.state.attachment.report)){
                if(_this.state.attachment.report.length > 0){
                    _sendDate.report = _this.state.attachment.report;
                }
            }
            const sendData = Object.assign({},v,_sendDate);
            _this.setState({
                attachment:{},
                fileList:{}
            },function(){
                _this.resetFields();
            });
            _this.props.dispatch(createImage(sendData,function(){
                message.success('新增检查信息成功',1)
            },function(){
                message.error('新增检查信息失败',1);
            },function(e){
                message.error('网络错误：'+e,1)
            }))
        })
    }
    normFile(e) {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    }
    addNewPatient(newOne){
        const _this=this,
            _user = _this.props.user,
            uid = _user.user.user_id,
            status = 1,
            opts = {
                userid: uid,
                status: status
            };
        this.props.dispatch(fetchPatients(opts,function(res){
            _this.setState({
                patients:res.content.list
            },function(){
                _this.selectChange(newOne.id)
            })
        },function(){
            message.error('获取亲友失败')
        }));
    }
    uploadChangeHandler(cate,info){
        const _this = this;
        return uploadChangeHandle(cate,info,_this)
    }
    uploadChange(info){
        const _this = this,
          status = info.file.status;
        switch(status){
            case 'uploading':
              console.log(info.file)
              /*const time = new Date(),
                _m = time.getMinutes(),
                _s = time.getSeconds(),
                _ms = time.getMilliseconds(),
                now = _m+':'+_s+':'+_ms;
                console.log('uploading',now)*/
            _this.setState({
                submitDisabled:true,
                fileListLen:info.fileList.length
            });
            break;
            case 'removed':
                const opts = `${_this.state.uuid}/${info.file.name}`;
                _this.props.dispatch(deleteDicom(opts,function(){
                    message.success('成功删除影像文件')
                },function(){
                    message.error('删除失败')
                }));
                _this.setState({
                    submitDisabled:false
                });
                dicomUpload.all = info.fileList.length;
            break;
            case 'done':
            message.success(`${info.file.name} 上传成功。`);
            _this.setState({
                submitDisabled:false
            })
            dicomUpload.all = info.fileList.length;
            break;
            case 'error':
            message.error(`${info.file.name} 上传失败。`);
            _this.setState({
                submitDisabled:false
            });
            break;
        }
    }
    deleteDicoms(){
        const _this = this,
          batchId = _this.state.uuid;
        _this.props.dispatch(deleteDicom(batchId,function(res){
            message.info('成功清除已上传文件');
            _this.props.form.resetFields(['upload']);
        },function(res){
            message.info('清除已上传文件失败');
        }));
        dicomUpload.all = 0;
        dicomUpload.confirm = null
    }
    beforeUpload(a){
        let len = ++dicomUpload.once;
        if((len+dicomUpload.all)>a){
            if(!dicomUpload.confirm){
                Modal.info({
                    title: `上传总量超限`,
                    content:(<div>总计上传文件数量不得超过{a}个<br /><br />建议您您打包重新上传；<br />如果您需要重新打包上传，之前上传的文件将被清除！</div>),
                    okText: `重新打包上传(清除现有文件)`,
                    onOk:this.deleteDicoms.bind(this),
                    onCancel:function(){
                        dicomUpload.confirm = null
                    }
                })
                dicomUpload.confirm = true
            }
            return false
        }
    }
    resetUploadCount(){
        dicomUpload.once = 0
    }
    selectChange(t){
        const _this = this;
        this.setState({
            defValue:t
        },function(){
            _this.props.form.setFieldsValue({pid:t})
        })
    }
    fileTypeLimit(types,file){
        const fileType = file.type,
          typeStr = types.join('、');
        let isOk = false;
        for(let i = 0;i<types.length;i++){
            try{
                isOk = new RegExp(types[i]).test(fileType);
                if(isOk){
                    break;
                }
            }catch(e){consloe.log(e)}
        }
        if(!isOk){
            message.error(`您上传文件的格式只能是：${typeStr}格式`);
            return isOk
        }

    }
    render(){
        const { getFieldProps } = this.props.form;
        const choosePatientProps = getFieldProps('pid', {
            rules: [
                { required: true, message: '请选择您的亲友' }
            ],
            onChange:this.selectChange.bind(this)
        });
        const imageType = getFieldProps('check_item_name', {
            rules: [
                { required: true,message: '请输入检查项目类型' }
            ]
        });
        const institution = getFieldProps('institution', {
            rules: [
                { required: true,message: '请选输入机构名称' }
            ]
        });
        const symptom = getFieldProps('symptom', {
            rules: [
                { required: true,message: '请选输入症状描述' }
            ]
        });
        const diagnosis = getFieldProps('diagnosis', {
            rules: [
                { required: true,message:"请输入临床诊断结果" }
            ]
        });
        const upload = getFieldProps('upload', {
            valuePropName: 'fileList',
            normalize: this.normFile,
            onChange: this.uploadChange,
            rules: [
                { required: true,
                    type:'array',
                    message: '必须上传有效影片' }
            ]
        });
        const files_report = getFieldProps('files_report', {
            valuePropName: 'fileList',
            normalize: this.normFile,
            onChange: this.uploadChangeHandler.bind(this,'report'),
            rules: [
                { required: false,
                    type:'array',
                    message: '必须上传有效影片' }
            ]
        });
        return (
            <Form horizontal form={this.props.form}>
                <div>
                    <FormItem
                        {...formItemLayout}
                        label="亲友"
                        help="请选择即将上传影像的亲友"
                    >
                        {this.createPatientsSelect(choosePatientProps)}
                    </FormItem>
                    <FormItem wrapperCol={formItemLayout.noLabel}>
                        <NewPatient
                            user={this.props.user}
                            dispatch={this.props.dispatch}
                            _r = {this.context.router}
                            addNewPatient={this.addNewPatient}
                        />
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="检查项目"
                        help="例如：‘脑部CT’或‘胸部CR’"
                    >
                        <Input {...imageType} placeholder="请输入检查项目类型" />
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="拍摄机构"
                        help="拍摄影像的医院或机构的名称"
                    >
                        <Input {...institution} placeholder="请输入拍摄机构名称" />
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="临床诊断"
                        help="请参考诊断书录入"
                    >
                        <Input type="textarea" {...diagnosis} placeholder="请输入临床诊断" rows={4}/>
                    </FormItem>
                    <FormItem
                      {...formItemLayout}
                      label="症状描述"
                      help="请参考病例录入"
                    >
                        <Input type="textarea" rows={4} {...symptom} placeholder="请输入症状描述" />
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="上传影像"
                        help={`请上传DICOM影像`}
                    >
                        <Upload
                            {...upload}
                            beforeUpload={this.beforeUpload.bind(this,20,20)}
                            name="file"
                            action= {`${API_URL}${DICOMS}/${this.state.uuid}?accessToken=${this.state.user.accessToken}`}
                            multiple={true}
                        >
                            <Button type="ghost"
                                onClick={this.resetUploadCount.bind(this)}
                                disabled={this.state.submitDisabled}
                            >
                                <Icon type="upload" /> 选择影像文件并上传
                            </Button>
                        </Upload>
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="其他单据"
                        help={`请上传其他单据`}
                    >
                        <Upload
                            name='files'
                            action={`${API_URL}upload/study?accessToken=${this.state.user.accessToken}`}
                            multiple={true}
                            beforeUpload = {this.fileTypeLimit.bind(this,['jpg','gif','png','jpeg'])}
                            {...files_report}
                        >
                            <Button type="ghost" >
                                <Icon type="upload" /> 选择报告图片并上传
                            </Button>
                        </Upload>
                    </FormItem>

                    <FormItem wrapperCol={formItemLayout.noLabel}>
                        <Button type="primary"
                            disabled={this.state.submitDisabled}
                            onClick={this.handleSubmit}
                        >
                            提交
                        </Button>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <Button type="ghost" onClick={this.resetFields}>重置</Button>
                    </FormItem>
                </div>
            </Form>
        )
    }
}

export default FormAddImage = Form.create()(FormAddImage);